<template>
  <el-dialog
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :title="adding ? '新增教练' : '编辑教练'"
    :visible.sync="visiable"
    append-to-body
    lock-scroll
    modal
    modal-append-to-body
    show-close
    width="40%"
    @close="close"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="right"
      label-width="150px"
    >
      <el-form-item label="教练姓名: " prop="userName">
        <el-input v-model="form.userName" placeholder="请输入关键字" />
      </el-form-item>
      <!--      <el-form-item label="教练账号: " prop="nickName">-->
      <!--        <el-input v-model="form.nickName" :disabled="!adding" placeholder="请输入教练账号" />-->
      <!--      </el-form-item>-->

      <el-form-item label="所在单位: " prop="unitName">
        <el-input v-model="form.unitName" placeholder="请输入所在单位" />
      </el-form-item>
      <el-form-item label="性别: " prop="sex">
        <el-select v-model="form.sex" placeholder="全部">
          <el-option
            v-for="item in sexList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="头像:" prop="avatar">
        <el-upload
          :before-upload="beforeAvatarUpload"
          :http-request="handleUpload"
          :on-success="handleAvatarSuccess"
          :show-file-list="false"
          class="avatar-uploader"
        >
          <img v-if="imageUrl" :src="imageUrl" class="preview-avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>

      <el-form-item label="密  码:" prop="password">
        <el-input
          v-model="form.password"
          placeholder="请输入密码"
          show-password
          type="password"
        />
      </el-form-item>
      <el-form-item label="可约时间:" prop="time">
        <div class="order-time">
          <el-row
            v-for="(item, index) in orderTime"
            :key="'order-time-' + index"
            class="order-item-item"
          >
            <el-col :span="10">
              <el-select v-model="item.week" style="width: 100%">
                <el-option
                  v-for="wItem in weeks"
                  :key="wItem.label"
                  :label="wItem.label"
                  :value="wItem.value"
                />
              </el-select>
            </el-col>
            <el-col :offset="1" :span="10">
              <el-select v-model="item.time" style="width: 100%">
                <el-option
                  v-for="tItem in times"
                  :key="tItem.label"
                  :label="tItem.label"
                  :value="tItem.value"
                />
              </el-select>
            </el-col>
            <el-col :span="2" :offset="1">
              <el-button
                icon="el-icon-close"
                type="text"
                @click="clickOnDeleteTimeItem(item, index)"
              />
            </el-col>
          </el-row>
        </div>
        <el-button
          icon="el-icon-plus"
          style="width: 100%"
          @click="clickOnAddTimeItem"
        />

        <!--        <el-date-picker-->
        <!--          v-model="form.time"-->
        <!--          end-placeholder="End date"-->
        <!--          range-separator="To"-->
        <!--          start-placeholder="Start date"-->
        <!--          type="datetimerange"-->
        <!--        />-->
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="confirm">保存</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { coachAdd, UpdateCoach, UploadFile } from '@/api/api'
import { mapGetters } from 'vuex'

const AddingRules = {
  avatar: [{ required: true, message: '请上传教练头像', trigger: 'blur' }],
  userName: [{ required: true, message: '请输入教练姓名', trigger: 'blur' }],

  // nickName: [
  //   { required: true, message: '请输入教练账号', trigger: 'blur' }
  // ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  unitName: [{ required: true, message: '请输入所在单位', trigger: 'blur' }]
}

const EditingRules = {
  avatar: [{ required: true, message: '请上传教练头像', trigger: 'blur' }],
  userName: [{ required: true, message: '请输入教练姓名', trigger: 'blur' }],

  // nickName: [
  //   { required: true, message: '请输入教练账号', trigger: 'blur' }
  // ],

  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  unitName: [{ required: true, message: '请输入所在单位', trigger: 'blur' }]
}

export default {
  name: 'CoachEditDialog',

  data() {
    return {
      coachId: '',
      times: [],
      weeks: [
        {
          label: '周一',
          value: '周一'
        },
        {
          label: '周二',
          value: '周二'
        },
        {
          label: '周三',
          value: '周三'
        },
        {
          label: '周四',
          value: '周四'
        },
        {
          label: '周五',
          value: '周五'
        },
        {
          label: '周六',
          value: '周六'
        },
        {
          label: '周日',
          value: '周日'
        }
      ],
      adding: false,
      visiable: false,
      imageUrl: '',

      form: {
        avatar: '',
        nickName: '',
        userName: '',
        sex: '1',
        unitName: ''
        // time: '',
        // week: 0,
        // startTime: '',
        // endTime: ''
      },
      sexList: [
        {
          label: '男',
          value: 1
        },
        {
          label: '女',
          value: 2
        }
      ],

      orderTime: [],
      rules: this.adding ? AddingRules : EditingRules
    }
  },
  computed: {
    ...mapGetters(['token'])
  },
  mounted() {
    this.structureTimeData()
  },
  methods: {
    updateForm(form) {
      this.form.nickName = form.nickName
      this.form.sex = form.sex
      this.form.userName = form.userName
      this.form.unitName = form.unitName
      this.form.avatar = form.avtar
      this.imageUrl = form.avtar
      this.orderTime = form.orderTime.map((item) => {
        return {
          week: item.week,
          time: `${item.startTime}-${item.endTime}`
        }
      })
      this.coachId = form.userId

      console.log('this.form', this.form)
      // if (!this.adding) {
      //   this._getCoachDetail()
      // }
    },
    structureTimeData() {
      const arr = [9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
      arr.forEach((item) => {
        const str = `${item < 10 ? '0' + item : item}:00:00-${item + 1}:00:00`
        this.times.push({
          label: str,
          value: str
        })
      })
    },
    clickOnDeleteTimeItem(item, index) {
      this.orderTime.splice(index, 1)
    },
    clickOnAddTimeItem() {
      this.orderTime.push({
        week: '周一',
        time: '09:00:00-10:00:00'
      })
    },
    // async _getCoachDetail() {
    //   try {
    //     const { code, msg, data } = await GetCoachDetail({ coachId: this.coachId })
    //     console.log(code, msg, data)
    //   } catch (e) {
    //     console.error(e)
    //   }
    // },
    async handleUpload(file) {
      try {
        console.log('handle uplad', file)
        const header = {
          Authorization: this.token
        }

        const res = await UploadFile(file, header)
        console.log(res)
        const { msg, code, url } = res.data
        if (code !== 200) {
          this.$message.error(msg)
          return
        }
        this.form.avatar = url
      } catch (e) {
        console.error(e)
      }
    },
    close() {
      this.visiable = false
      this.$emit('closed')
    },
    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.handleUpdateCoach()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像图片只能是 jpg/jpeg/png格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    async handleUpdateCoach() {
      if (!this.form) {
        return
      }
      // const startTime = this.form.time.split('-')[0]
      // const endTime = this.form.time.split('-')[1]
      //
      // console.log(endTime, this.form.time.split('-'))

      // if (!this.orderTime || this.orderTime.length <= 0) {
      //   this.$message.info('请输入可预约时间')
      //   return
      // }
      const orderTime = this.orderTime && this.orderTime.length > 0 ? this.orderTime.map((item) => {
        // const week = this.weeks[item.week].label

        return {
          week: item.week,
          startTime: item.time.split('-')[0],
          endTime: item.time.split('-')[1]
        }
      }) : []
      // console.log(orderTime)

      try {
        const params = {
          avatar: this.form.avatar,
          nickName: this.form.nickName,
          sex: this.form.sex,
          unitName: this.form.unitName,
          userName: this.form.userName,
          password: this.form.password,
          reserveDate: '',
          coachId: this.adding ? undefined : this.coachId,
          orderTime
        }

        let res = null
        if (this.adding) {
          res = await coachAdd(params)
        } else {
          res = await UpdateCoach(params)
        }
        const { data } = res
        this.$message(data.msg)

        // this.getCoachData(this.formInline)
        this.close()
        this.$emit('updated')
      } catch (e) {
        console.error(e)
      }
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.preview-avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.order-time {
  .order-item-item {
    margin-bottom: 10px;
  }
}
</style>
